//
//  PullUpMenuView.m
//  EZ Tracker
//
//  Created by FENGYL on 2016/11/25.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "PullUpMenuView.h"
#import "UIView+XL.h"
#import "NetworkCommand.h"
#import "WGS84TOGCJ02.h"
#import "NSDate+FMGExtension.h"

#import <CoreLocation/CoreLocation.h>

@interface PullUpMenuView()

@property (strong, nonatomic) NSTimer *timer;
@property (assign, nonatomic) NSInteger time;

@property (strong , nonatomic) UIPanGestureRecognizer * panGestureRecognizer;
@property (strong , nonatomic) UISwipeGestureRecognizer * swipeUpGestureRecognizer;
@property (strong , nonatomic) UISwipeGestureRecognizer * swipeDownGestureRecognizer;
@property (assign , nonatomic) CGFloat pullUpViewBeginY;

@property (weak, nonatomic) IBOutlet UIView *pullUpView;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *informationTimeLabel;

@property (weak, nonatomic) IBOutlet UILabel *locationLatitudeLabel;
@property (weak, nonatomic) IBOutlet UILabel *locationLongitudeLabel;
@property (weak, nonatomic) IBOutlet UILabel *locationAddressLabel;

@property (weak, nonatomic) IBOutlet UILabel *deviceSignalLabel;
@property (weak, nonatomic) IBOutlet UILabel *deviceBatteryLabel;
@property (weak, nonatomic) IBOutlet UILabel *deviceSpeedLabel;
@property (weak, nonatomic) IBOutlet UILabel *deviceUserActivityLabel;
@property (weak, nonatomic) IBOutlet UILabel *deviceModeLabel;
@property (weak, nonatomic) IBOutlet UILabel *deviceAccuracyLabel;
@property (weak, nonatomic) IBOutlet UILabel *deviceSatelliteLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pullUpViewHeight;


@end

@implementation PullUpMenuView

-(NSTimer *)timer{
    
    if (!_timer) {
        
        _time = 0;
        
//        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0/100.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
//            
//            _time++;
//            
//            if (_time > 100) {
//                
//                [_timer invalidate];
//                
//            }
//            
//        }];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 100.0  target:self selector:@selector(initTimer) userInfo:nil repeats:YES];
        
    }
    
    return _timer;
    
}

#pragma makr 初始化定时器
-(void)initTimer{
    
    _time++;
    
    if (_time > 100) {
        
        [_timer invalidate];
        
    }
    
}

- (instancetype)initWithPullUpMenuView
{
    self = [super init];
    if (self) {
        
        self = [[NSBundle mainBundle] loadNibNamed:@"PullUpMenuView" owner:nil options:nil].lastObject;
        
        self.frame = CGRectMake( 0, [UIScreen mainScreen].bounds.size.height - self.pullUpView.height, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - [[UIApplication sharedApplication] statusBarFrame].size.height);
        
        self.panGestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(setUpGestureRecognizer:)];
        
        
        
        self.swipeUpGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(setUpSwipeGestureRecognizer:)];
        
        self.swipeUpGestureRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
        
        self.swipeDownGestureRecognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(setUpSwipeGestureRecognizer:)];
        
        self.swipeDownGestureRecognizer.direction = UISwipeGestureRecognizerDirectionDown;
        
        
        [self addGestureRecognizer:self.panGestureRecognizer];
        
//        [self addGestureRecognizer:self.swipeUpGestureRecognizer];
        
//        [self addGestureRecognizer:self.swipeDownGestureRecognizer];
        
        self.pullUpViewBeginY = self.y;
        
        [self setUpPullUpView];
        
    }
    return self;
}

#pragma mark 初始化
-(void)setUpPullUpView{
    
    [self.timeLabel setText:@""];
    
    [self.informationTimeLabel setText:@"Device Added:Unkonw"];
    
    [self.locationLatitudeLabel setText:@""];
    
    [self.locationLongitudeLabel setText:@""];
    
    [self.locationAddressLabel setText:@"No data"];
    
    [self.deviceModeLabel setText:@"Mode Not Found"];
    
}

#pragma mark 设置菜单文字
-(void)setUpPullUpViewForTrackPoiDataResponseObject:(NSArray *)trackPoiDataresponseObject StatusDataResponseObject:(NSArray *)statusDataResponseObject{
    
    NSDictionary *dict;
    NSDictionary *statusDict;
    
    if ([[trackPoiDataresponseObject firstObject] class] != [NSNull class]) {
        
        dict = [trackPoiDataresponseObject lastObject];
        
    }
    
    if ([[statusDataResponseObject firstObject] class] != [NSNull class]) {
        
        statusDict = [statusDataResponseObject lastObject];
        
    }
    
    if (statusDict) {
        
        //日期
        NSString *timestamp = [statusDict valueForKey:NC_GPSTIME];
        
        if (timestamp) {
            
            NSDate *gpsTimeDate = [NetworkCommand TimestampChangeDate:timestamp];
            
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
            
            dateFormatter.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];

            
            [dateFormatter setDateFormat:@"dd/MM/yyyy   hh:mmaa"];
            
            NSString *gpsTimeString = [dateFormatter stringFromDate:gpsTimeDate];
            
            NSLog(@"gps time %@",gpsTimeString);
            
            [self.timeLabel setText:gpsTimeString];
            
        }
        
        
        //坐标
        NSNumber *latitude = [statusDict valueForKey:NC_LAT];
        NSNumber *longitude = [statusDict valueForKey:NC_LNG];
        
        CLLocationCoordinate2D locationCoordinate2D = CLLocationCoordinate2DMake([latitude doubleValue], [longitude doubleValue]);
        
        if (![WGS84TOGCJ02 isLocationOutOfChina:locationCoordinate2D]) {
            
            locationCoordinate2D = [WGS84TOGCJ02 transformFromWGSToGCJ2:locationCoordinate2D];
            
        }
        
        [self.locationLatitudeLabel setText:[NSString stringWithFormat:@"%f",locationCoordinate2D.latitude]];
        [self.locationLongitudeLabel setText:[NSString stringWithFormat:@"%f",locationCoordinate2D.longitude]];
        
        //地址
        
        CLGeocoder *geocoder = [[CLGeocoder alloc]init];
        
        CLLocation *geocoderLocation = [[CLLocation alloc]initWithLatitude:locationCoordinate2D.latitude longitude:locationCoordinate2D.longitude];
        
        [geocoder reverseGeocodeLocation:geocoderLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            
            for (CLPlacemark *placemark in placemarks) {
                
                NSArray *place = [placemark.addressDictionary valueForKey:@"FormattedAddressLines"];
                
                NSLog(@"place name %@",[place firstObject]);
                
                [self.locationAddressLabel setText:[place firstObject]];
                
            }
            
        }];
        
//        if ([[dict valueForKey:NC_ADDRESS] class] != [NSNull class]) {
//            
//            NSString *address = [dict valueForKey:NC_ADDRESS];
//            
//            [self.locationAddressLabel setText:address];
//            
//        }
        
        //signal
        NSNumber *signal = [dict valueForKey:NC_HIGH];
        
        [self.deviceSignalLabel setText:[NSString stringWithFormat:@"Signal  %d%%",[signal intValue]]];
        
        
        //battery
        NSNumber *battery = [statusDict valueForKey:NC_POWER_VALUE];
        
        [self.deviceBatteryLabel setText:[NSString stringWithFormat:@"Battery  %d%%",[battery intValue]]];
        
        //speed
        NSNumber *speed = [dict valueForKey:NC_SPEED];
        
        //超过三分钟速度归零
        NSDate *gpsTimeDate = [NetworkCommand TimestampChangeDate:timestamp];
        NSDateComponents *dateComponents = [gpsTimeDate intervalToNow];
        NSInteger second = dateComponents.second;
        
        if (second > 180) {
            
            speed = @(0);
            
        }
        
        [self.deviceSpeedLabel setText:[NSString stringWithFormat:@"Speed  %.2f km/h",[speed doubleValue]]];
        
        //user activity available
        NSNumber *activity = [statusDict valueForKey:NC_CONN_STATUS];
        
        if ([activity intValue] == 0) {
            
            [self.deviceUserActivityLabel setText:@"User Activity not available"];
            
        }else{
            
            [self.deviceUserActivityLabel setText:@"User Activity available"];
            
        }
        

        //satellite
        NSNumber *satellite = [dict valueForKey:NC_STATES];
        
        [self.deviceSatelliteLabel setText:[NSString stringWithFormat:@"Satellite  %d",[satellite intValue]]];
        
        
        //mode
        NSNumber *modeType = [statusDict valueForKey:NC_UP_MODE];
        
        if ([modeType intValue] == 1) {
            
            [self.deviceModeLabel setText:@"Mode  GPS"];
            
        }else if ([modeType intValue] == 2){
            
            [self.deviceModeLabel setText:@"Mode  LBS"];
            
        }else{
            
            [self.deviceModeLabel setText:@"Mode Not Found"];
            
        }
        
    }
    
    
}

#pragma mark 隐藏上拉条
-(void)hidePullUpView{
    
    self.pullUpViewHeight.constant = 0;
    
}

#pragma mark 手势

-(void)setUpSwipeGestureRecognizer:(UISwipeGestureRecognizer *)gesture{
    
    if (gesture.direction == UISwipeGestureRecognizerDirectionUp) {
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.y = [[UIApplication sharedApplication] statusBarFrame].size.height;
            
        }];
        
    }else{
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.y = [UIScreen mainScreen].bounds.size.height - 30;
            
        }];
        
    }
    
}

-(void)setUpGestureRecognizer:(UIPanGestureRecognizer *)gesture{
    
    CGPoint translation = [gesture translationInView:gesture.view];
    NSLog(@"%@",[NSString stringWithFormat:@"(%0.0f, %0.0f)", translation.x, translation.y]);
    
    self.y = self.pullUpViewBeginY + translation.y;
    
    if (self.y < [[UIApplication sharedApplication] statusBarFrame].size.height) {
        
        self.y =[[UIApplication sharedApplication] statusBarFrame].size.height;
        
    }else if (self.y > [UIScreen mainScreen].bounds.size.height - 30){
        
        self.y = [UIScreen mainScreen].bounds.size.height - 30;
        
    }
    
    if (gesture.state == UIGestureRecognizerStateBegan) {
        
        [self.timer fire];
        
    }
    
    
    if (gesture.state == UIGestureRecognizerStateEnded) {
        
        [self.timer invalidate];
        
        self.timer = nil;
        
        NSLog(@"time %ld",(long)self.time);
        
        if (self.time > 30) {
            //拖
            if (self.pullUpViewBeginY + translation.y > [UIScreen mainScreen].bounds.size.height / 2) {
                
                [UIView animateWithDuration:0.3 animations:^{
                    
                    self.y = [UIScreen mainScreen].bounds.size.height - 30;
                    
                } completion:^(BOOL finished) {
                    
                    self.pullUpViewBeginY = self.y;
                    
                }];
                
            }else{
                
                [UIView animateWithDuration:0.3 animations:^{
                    
                    self.y = [[UIApplication sharedApplication] statusBarFrame].size.height;
                    
                } completion:^(BOOL finished) {
                    
                    self.pullUpViewBeginY = self.y;
                    
                }];
                
                
                
            }
            
        }else{
            //扫
            if (translation.y > 0) {
                
                [UIView animateWithDuration:0.3 animations:^{
                    
                    self.y = [UIScreen mainScreen].bounds.size.height - 30;
                    
                } completion:^(BOOL finished) {
                    
                    self.pullUpViewBeginY = self.y;
                    
                }];
                
            }else if (translation.y < 0){
                
                [UIView animateWithDuration:0.3 animations:^{
                    
                    self.y = [[UIApplication sharedApplication] statusBarFrame].size.height;
                    
                } completion:^(BOOL finished) {
                    
                    self.pullUpViewBeginY = self.y;
                    
                }];
                
            }
            
        }
        
        
        
        
        
        
        
    }
    
    self.changeCoverViewAlpha(self.y);
    
}

//-(void)setUpPanGestureRecognizer:(UIPanGestureRecognizer *)gesture{
//    
//    CGPoint translation = [gesture translationInView:gesture.view];
//    NSLog(@"%@",[NSString stringWithFormat:@"(%0.0f, %0.0f)", translation.x, translation.y]);
//    
//    if (self.transform.ty < [[UIApplication sharedApplication] statusBarFrame].size.height) {
//        
//        self.y =[[UIApplication sharedApplication] statusBarFrame].size.height;
//        
//    }else if (self.y > [UIScreen mainScreen].bounds.size.height - 30){
//        
//        self.y = [UIScreen mainScreen].bounds.size.height - 30;
//        
//    }
//    
//    
//    
//    if (gesture.state == UIGestureRecognizerStateEnded) {
//        
//        if (self.pullUpViewBeginY + translation.y > [UIScreen mainScreen].bounds.size.height / 2) {
//            
//            [UIView animateWithDuration:0.3 animations:^{
//                
//                self.y = [UIScreen mainScreen].bounds.size.height - 30;
//                
//            } completion:^(BOOL finished) {
//                
//                self.pullUpViewBeginY = self.y;
//                
//            }];
//            
//        }else{
//            
//            [UIView animateWithDuration:0.3 animations:^{
//                
//                self.y = [[UIApplication sharedApplication] statusBarFrame].size.height;
//                
//            } completion:^(BOOL finished) {
//                
//                self.pullUpViewBeginY = self.y;
//                
//            }];
//            
//            
//            
//        }
//        
//        
//        
//        
//        
//    }
//    
//    
//    
//    self.changeCoverViewAlpha(self.y);
//    
//}



@end
